/* 请求模块 */
import constant from '@/common/constant.js';
import LoginUtil from '@/main/common/LoginUtil.js';
import CacheUtil from '@/main/common/CacheUtil.js';

/**
 * get请求
 */
function get(url = '', param = {}, header = {}, isLoad = true) {
	return request('get', url, param, header, isLoad);
}
/**
 * post请求
 */
function post(url = '', param = {}, header = {}, isLoad = true) {
	return request('post', url, param, header, isLoad);
}
/**
 * 请求数据处理
 */
function request(method, url, param, header = {}, isLoad) {
	return new Promise((resolve, reject) => {
		// 处理url
		url = constant.baseUrl + url;
		// 默认数据
		param = param || {};
		header = header || {};
		//header
		let token = CacheUtil.getToken();
		if (token) {
			if(
				url.includes('/api/sendSms') ||
				url.includes('/api/login')
			){
			}else{
				header.Authorization = "Api " + token;
			}
		}
		header.packageName = constant.packageName;
		// #ifdef APP-PLUS
		if(getApp().globalData.deviceModel){
			header.mobileSpec = getApp().globalData.deviceModel;
		}
		// #endif
		
		// 加载动画
		if (isLoad) {
			uni.showLoading({
				title: typeof isLoad == 'string' ? isLoad : '数据加载中'
			});
		}
		
		console.log("http-url:" + url);
		console.log("http-header:" + JSON.stringify(header));
		console.log("http-param:" + JSON.stringify(param));
		// 发送请求
		uni.request({
			method: method,
			url: url,
			data: param,
			header: header,
			success: (res) => {
				console.log("http-数据:" + JSON.stringify(res.data));
				//3011008:登录已过期，请重新登录
				//3011005:账号已注销
				if(3011008 == res.data.code){
					uni.showToast({
						title:res.data.message,
						icon: 'none'
					})
					LoginUtil.logout()
					return
				}
				
				if(200 == res.data.code){
					resolve(res.data)
				}else{
					uni.showToast({
						title:res.data.message,
						icon: 'none'
					})
					reject(res.data)
				}
			},
			fail: (res) => {
				reject(res)
			},
			complete:()=>{
				// 关闭动画
				if (isLoad) {
					uni.hideLoading();
				}
			}
		});
	})
}

/**
 * 由于此接口调用比较多，所以统一处理
 */
function getUser(){
	return new Promise((resolve, reject) => {
		get('/api/getLoginUser').then(res => {
			resolve(res);
			//处理统一的方法
			if (0 == res.data.vip) {
				CacheUtil.setVip(true)
			} else {
				CacheUtil.setVip(false)
			}
			
		})
	});
}

/**
 * 由于此接口调用比较多，所以统一处理
 */
function updateUser(params){
	return new Promise((resolve, reject) => {
		params['id'] = uni.getStorageSync('userId')
		post('/api/user/updateUser', params).then(res => {
			resolve(res);
		})
	});
}

module.exports = {
	get,
	post,
	request,
	getUser,
	updateUser
}